package chapter07;

import java.sql.*;
import java.util.Scanner;

public class Test01_connectDB {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement =null;
        ResultSet rs = null;
        try {
            //1、注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、连接数据库
            String url = "jdbc:mysql://localhost:3306/" +
                    "studentmanagement?serverTimezone=GMT%2B8&useSSL=false";
            connection = DriverManager.getConnection(url,
                    "root", "");
            //得到statement对象
            statement = connection.createStatement();
            //执行sql语句 得到结果集
            //只想查到张三同学
            System.out.println("请输入要查询学生的信息：");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.nextLine();
            String sql = "select * from student where sname='"+name+"'";
            rs = statement.executeQuery(sql);
            //取出数据
            while(rs.next()){
                //根据字段名和字段类型取数据
                int id = rs.getInt("id");
                String sno = rs.getString("sno");
                String sname = rs.getString("sname");
                String sgrade = rs.getString("sgrade");
                System.out.println(id+":"+sno+":"+sname+":"+sgrade);
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }finally {
                    rs = null;
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }finally {
                    statement = null;
                }
            }if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }finally {
                    connection = null;
                }
            }
        }

    }
}
